package ui.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.andlei.baseapp.R;

import org.json.JSONObject;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import base.BaseBean;
import base.activity.BaseLayoutActivity;
import bean.DouBanBean;
import netWork.NetUtils;
import utils.Logger;
import utils.TxtUtils;
import widget.BswRecyclerView.BswRecyclerView;
import widget.BswRecyclerView.ConvertViewCallBack;
import widget.BswRecyclerView.OnLoadListener;
import widget.BswRecyclerView.RecyclerViewHolder;

/**
 * 《一个Android工程的从零开始》
 *
 * @author 半寿翁
 * @博客：
 * @CSDN http://blog.csdn.net/u010513377/article/details/74455960
 * @简书 http://www.jianshu.com/p/1410051701fe
 */
public class MainActivity extends BaseLayoutActivity {

    private Button view, mergeBtn2;
    private int count = 0;

    private EditText clickEt, port;
    private TextView tv_content;
    private int intPort;
    private Socket socket;
    private OutputStream os;
    private Button btn_connect,
            btn_send,
            btn_stop;
    private BswRecyclerView<BaseBean> bswList;

    private NetUtils netUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(R.string.title);

        netUtils = new NetUtils(mContext, netRequestCallBack);
        netUtils.get("top250", new HashMap<String, Object>(), DouBanBean.class, null, false);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @SuppressLint("InflateParams")
    @Override
    protected void findViews() {
        view = getView(R.id.merge_btn);
        mergeBtn2 = getView(R.id.merge_btn2);
        clickEt = getView(R.id.click_et);
        bswList = getView(R.id.bsw_list);
        port = getView(R.id.port);
        tv_content = getView(R.id.tv_content);
        btn_connect = getView(R.id.btn_connect);
        btn_send = getView(R.id.btn_send);
        btn_stop = getView(R.id.btn_stop);
    }

    private List<BaseBean> getBaseBeans() {
        List<BaseBean> baseBeans = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            baseBeans.add(new BaseBean());
        }
        return baseBeans;
    }

    @Override
    protected void formatViews() {
        btn_stop.setOnClickListener(this);
        btn_send.setOnClickListener(this);
        btn_connect.setOnClickListener(this);
        bswList.initAdapter(R.layout.tv_list_item, convertViewCallBack);
        bswList.setLayoutManager().setDecoration();
        bswList.setLoadListener(new OnLoadListener() {
            @Override
            public void loadData() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } finally {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    bswList.addData(getBaseBeans());
                                    Logger.i(getName(), "加载到第" + bswList.getItemCount() + "个");
                                }
                            });
                        }
                    }
                }).start();
                Logger.i(getName(), "加载了");
            }

            @Override
            public boolean canLoadMore() {
                return true;
            }

            @Override
            public boolean allLoaded() {
                return false;
            }
        });
        bswList.setData(getBaseBeans());
        setOnClickListener(R.id.merge_btn, R.id.merge_btn2, R.id.click_et);
    }

    @Override
    protected void formatData() {
        mergeBtn2.setText(String.format(Locale.CHINA, TxtUtils.getText(mContext, R.string.all), "55555"));
//        view.setText(String.format(Locale.CHINA, TxtUtils.getText(mContext, R.string.all), "12345"));
        if (getIntent() != null) {
            view.setText(getIntent().getStringExtra("name"));
        }
    }

    @Override
    protected void getBundle(Bundle bundle) {
    }

    private ExecutorService mThreadPool  =  Executors.newCachedThreadPool();//这就是个线程池管理
    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.merge_btn:
                view.setText(getName(BaseBean.class));
                Logger.i("111", count + "");
                break;

            case R.id.merge_btn2:
//                backTo(TestActivity.class);
//                jumpTo(TestActivity.class);
                finishActivity();
                break;
                /*
            建立连接
             */
            case R.id.btn_connect:
                tv_content.setText("");
                String port = this.port.getText().toString();
                if (!"".equals(port)) {
                    intPort = Integer.parseInt(port);
                } else {
                    Toast.makeText(MainActivity.this, "输入端口号", Toast.LENGTH_SHORT).show();
                    return;
                }
                mThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            /*建立请求连接*/
                            socket = new Socket("192.168.0.108", intPort);
                            System.out.println(socket.isConnected());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (socket.isConnected()) {
                                        tv_content.setText("建立连接成功！" + intPort);
                                    } else {
                                        tv_content.setText("建立连接失败！" + intPort);
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                });
                break;
            //发送数据
            case R.id.btn_send:
                sendMessageToServer();
                break;
            //断开连接
            case R.id.btn_stop:
                dissConnection();
                break;
        }
    }

    /*
    发送数据给服务端
     */
    private void sendMessageToServer() {
        long l = System.currentTimeMillis();
        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("msgType", "");
            jsonObject.put("msgValue", "");
            jsonObject.put("msgTime", l + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    os = socket.getOutputStream();
                    os.write((jsonObject.toString() + "/n").getBytes("utf-8"));
                    // 数据的结尾加上换行符才可让服务器端的readline()停止阻塞
                    os.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /*
    断开 连接
     */
    private void dissConnection() {
        try {
            // 断开 客户端发送到服务器 的连接，即关闭输出流对象OutputStream
            os.close();
            // 断开 服务器发送到客户端 的连接，即关闭输入流读取器对象BufferedReader
            //br.close();
            // 最终关闭整个Socket连接
            socket.close();
            // 判断客户端和服务器是否已经断开连接
            System.out.println(socket.isConnected());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private ConvertViewCallBack<BaseBean> convertViewCallBack = new ConvertViewCallBack<BaseBean>() {
        @Override
        public BaseBean convert(RecyclerViewHolder holder, BaseBean baseBean, int position) {
            holder.setText(R.id.item_tv, "第" + (position + 1) + "项");
            return baseBean;
        }
    };

    private NetUtils.NetRequestCallBack netRequestCallBack = new NetUtils.NetRequestCallBack() {
        @Override
        public void success(String action, BaseBean baseBean, Map tag) {
            switch (action) {
                case "top250":
                    DouBanBean douBanBean = ((DouBanBean) baseBean);
                    System.out.println(douBanBean.toString());
                    break;
            }
        }

        @Override
        public void error(String action, Throwable e, Map tag) {

        }
    };
}
